/**
 * @file: 新增/编辑字典弹窗
 * @author: Lengxx
 * @date: 2024-06-26
 */
<template>
  <BasicModal
  :title="isEdit ? '编辑字典' : '新增字典'"
  v-bind="$attrs"
  width="400px"
  :loading="addLoading || editLoading"
  @register="register"
  @ok="onSubmit"
  >
    <Form
    :model="formState"
    :labelCol="{ style: { width: '80px' } }"
    >
      <FormItem label="字典名称" v-bind="validateInfos.name" >
        <Input v-model:value="formState.name" />
      </FormItem>
      <FormItem label="字典类型" v-bind="validateInfos.type" >
        <Input v-model:value="formState.type" />
      </FormItem>
      <FormItem label="字典编码" v-bind="validateInfos.code" >
        <Input v-model:value="formState.code" />
      </FormItem>
      <FormItem label="排序" >
        <Input type="number" v-model:value="formState.sort" />
      </FormItem>
      <FormItem label="描述" name="desc" >
        <Input v-model:value="formState.desc" />
      </FormItem>
    </Form>
  </BasicModal>
</template>

<script lang="ts" setup>
import { get, omit } from 'lodash-es'
import { ref, reactive } from 'vue'
import * as api from '@/api/dictionary'
import { useRequest } from '@vben/hooks'
import { ModalTypeEnum } from '@/enums/appEnum';
import { BasicModal, useModalInner } from '@/components/Modal'
import { Form, FormItem, Input } from 'ant-design-vue'
import { IDictionaryResp } from '@/api/dictionary/model';
import { addDictionaryModalRules } from '../settings';

const emits = defineEmits<{
  (e: 'submit'): void;
}>()

const { loading: addLoading, runAsync: addDictionary } = useRequest(api.addDictionary, { manual: true })
const { loading: editLoading, runAsync: editDictionary } = useRequest(api.editDictionary, { manual: true })

const isEdit = ref(false);

const formState = reactive<IDictionaryResp>({
  name: '',
  code: '',
  type: '',
  sort: 1,
  desc: '',
  createDate: '',
  id: ''
})

const { validate, resetFields, validateInfos } = Form.useForm(formState, addDictionaryModalRules);

const [register] = useModalInner(data => {
  const modalType = get(data, 'modalType', ModalTypeEnum.Add);

  if (modalType == ModalTypeEnum.Add) {
    isEdit.value = false;
    resetFields();
  } else {
    isEdit.value = true;
    for (let key in data) {
      if (Object.keys(formState).includes(key)) {
        formState[key] = data[key];
      }
    }
  }
})

async function onSubmit() {
  await validate();
  if (isEdit.value) {
    await editDictionary(omit(formState, 'createDate'));
  } else {
    await addDictionary(omit(formState, ['id', 'createDate']));
  }
  emits('submit');
}

</script>